﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using HundSunDBQryFrmClient.Utils;

namespace HundSunDBQryFrmClient
{
    internal class HundsunDB
    {
        static string key = "ttuAdhZvrSz4iOK9ZJJMEhLy7Cd6lJGOiWdaRVs1bw4=";
        static string iv = "EQtubEQcJmCoKDbpcBdh5w==";
        public static WebRsp getData(string url,string sql)
         {
            WebRsp webrsp = null;
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    byte[] key = Convert.FromBase64String(HundsunDB.key);
                    byte[] iv = Convert.FromBase64String(HundsunDB.iv);
                    byte[] value= AesHelp.Encrypt(sql, key, iv);
                    string reqcontentstr = $"value={Convert.ToBase64String(value)}";
                    HttpContent content = new StringContent(reqcontentstr);
                    var response = client.PostAsync(url, content).Result;
                    var contentstr = response.Content.ReadAsStringAsync().Result;
                    webrsp = JsonConvert.DeserializeObject<WebRsp>(contentstr);
                    
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                try
                {
                    if (webrsp == null || webrsp.data.Count == 0)
                    {

                        Thread.Sleep(500);
                        byte[] key = Convert.FromBase64String(HundsunDB.key);
                        byte[] iv = Convert.FromBase64String(HundsunDB.iv);
                        byte[] value = AesHelp.Encrypt(sql, key, iv);
                        string reqcontentstr = $"value={Convert.ToBase64String(value)}";
                        HttpContent content = new StringContent(reqcontentstr);
                        var response = client.PostAsync(url, content).Result;
                        var contentstr = response.Content.ReadAsStringAsync().Result;
                        webrsp = JsonConvert.DeserializeObject<WebRsp>(contentstr);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

            }
            return webrsp;
        }
    }
}
